document.addEventListener('fullscreenchange', () => {
  if (document.fullscreenElement) {
    document.getElementById("requestFullscreen").src = "./img/cancel_full_screen.png";
  } else {
    document.getElementById("requestFullscreen").src = "./img/full_screen.png";
  }
})

//页面加载完成执行
document.addEventListener('DOMContentLoaded', () => {
  document.getElementById("requestFullscreen").onclick = function(){
    if (document.fullscreenElement) {
      document.exitFullscreen()
    } else {
      document.body.requestFullscreen()
    }
  }
  loadData()
})


document.addEventListener("DOMContentLoaded", () => {
  document.getElementById("submitForm").addEventListener("submit", submit)
})

function submit(event){
  event.preventDefault()
  document.body.requestFullscreen()
  document.getElementById('main').style.display = 'none'
  var canvas = Mstsc.$("myCanvas")
  canvas.style.display = 'inline'
  canvas.width = screen.width
  canvas.height = screen.height
  const client = Mstsc.client.create(Mstsc.$("myCanvas"))

  const data = {
    ip: document.getElementById('ip').value,
    username: document.getElementById('username').value,
    password: document.getElementById('password').value
  }
  client.connect(data, (status, data) => {
    if(data && data.errno == -3008){
      alert("连接失败，请检查IP地址是否正确")
    }
    console.log(status, data)
    location.href = '/'
  })
}

const loadData = async() => {
  fetch('/rdp/list')
  .then(res => res.json())
  .then(data => {
    console.log(data)
    data.forEach(d => {
      const div = document.createElement('div')
      div.className = 'history-item'
      div.innerHTML = `<label>${d.ip}</label>`
      div.onclick = () => {
        document.body.requestFullscreen()
        document.getElementById('main').style.display = 'none'
        var canvas = Mstsc.$("myCanvas")
        canvas.style.display = 'inline'
        canvas.width = screen.width
        canvas.height = screen.height
        const client = Mstsc.client.create(Mstsc.$("myCanvas"))
      
        client.connecttoid(d.id, (status, data) => {
          if(data && data.errno == -3008){
            alert("连接失败，请检查IP地址是否正确")
          }
          console.log(status, data)
          location.href = '/'
        })
      }

      const del = document.createElement('div')
      del.className = 'delete'
      del.onclick = (e) => {
        e.stopPropagation()
        fetch(`/rdp/delete/${d.id}`, { method: 'POST'}).then(res => res.json()).then(data => {
          console.log(data)
          location.reload()
        })
      }
      div.appendChild(del)
      document.getElementById('history').appendChild(div)
    })
  })
}